<template>
  <div class="echart">
    <el-card
      :body-style="{
        padding: '20px',
        minHeight: 'calc(100vh - 100px)',
      }"
    >
      <div class="echartSet">
        <p>1.修改鼠标经过拐点tooltip展示数据的规则</p>
        <p>2.给拐点替换图片</p>
        <p>3.让图表自适应浏览器大小</p>
      </div>
      <div class="echart">
        <div
          id="statistics_eharts"
          class="statistics_eharts"
          ref="chart"
        ></div>
        <div
          id="statistics_eharts2"
          class="statistics_eharts"
          ref="chart2"
        ></div>
      </div>
      <div class="echart">
        <div
          id="statistics_eharts3"
          class="statistics_eharts"
          ref="chart3"
        ></div>
        <div
          id="statistics_eharts4"
          class="statistics_eharts"
          ref="chart4"
        ></div>
      </div>
      <!-- params.newOption.series = option
        let chartOption = Object.getOwnPropertyNames(this.chart._componentsMap)
        /* 获取图表中 magicType 模拟stack 点击 */
        chartOption.map((item: any) => {
          item.includes('toolbox') &&
            this.chart._componentsMap[item]._features['magicType'].model.iconPaths.stack.trigger('click')
      })-->
    </el-card>
  </div>
</template>

<script>
export default {
  name: "echart",
  components: {},
  data() {
    return {
      option: {
        title: {
          text: "用户数量/领取数量",
          textStyle: {
            color: "#000",
            fontSize: 16,
          },
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
          },
          textStyle: {
            align: "left", //文本左对齐
          },
          //改变鼠标移上去，修改图表数据的显示格式（数据的百位的时候加‘,’）
          formatter: function (params, ticket, callback) {
            var res = "" + params[0].name;
            for (var i = 0; i < params.length; i++) {
              let oSpan =
                '<span style="background:' +
                params[i].color +
                ';width:10px;height:10px;border-radius: 50%;display: inline-block;marign-right:5px;marign-bottom:5px"></span>';
              res +=
                "<br/>" +
                oSpan +
                " " +
                params[i].seriesName +
                " : " +
                params[i].value
                  .toString()
                  .replace(/(?=(\B)(\d{2})$)/, ",$1");
            }
            return res;
          },
        },
        legend: {
          left: "580",
          data: ["用户数量", "领取数量"], //统计的数据
        },
        grid: {
          bottom: "3%",
          left: "5%",
          right: "7%",
          containLabel: true,
        },
        xAxis: [
          {
            type: "category",
            //x轴字体颜色
            axisLine: {
              lineStyle: {
                color: "#000",
              },
            },
            splitLine: {
              show: false, //隐藏网格
            },
            data: [], //x轴的数据
            axisPointer: {
              type: "shadow",
              shadowStyle: {
                // 阴影指示器样式设置
                color: "rgba(1,127,90,0.1)", // 阴影颜色
              },
              splitLine: {
                show: false, //隐藏网格
              },
              splitArea: {
                show: false, //隐藏网格
              },
            },
            axisLabel: {
              show: true,
            },
          },
        ],
        //如果要用到2个y轴，就需要配置两个y轴
        yAxis: [
          {
            type: "value",
            x: "center",
            name: "（用户数量）",
            min: 0,
            // max: 100,
            show: true,
            //y轴颜色
            axisLine: {
              show: true,
              lineStyle: {
                color: "#000",
              },
            },
            splitLine: {
              show: true, //隐藏网格
            },
            splitArea: {
              show: false, //隐藏网格背景
            },
          },
          {
            type: "value",
            name: "（领取数量）",
            x: "center",
            min: 0,
            // max: 100,
            //y轴颜色
            axisLine: {
              show: true, //是否显示y轴的竖线
              lineStyle: {
                color: "#000",
              },
            },
            splitLine: {
              show: false, //隐藏网格
            },
            splitArea: {
              show: false, //隐藏网格背景
            },
          },
        ],
        series: [], //图表的数据
      },
    };
  },
  methods: {
    chartsInfo() {
      this.option.series = [];
      let timeData = [],
        userData = [],
        receiveData = [],
        //模拟后台返回的数据
        res = {
          xAxis: [
            "04/24",
            "04/25",
            "04/26",
            "04/27",
            "04/28",
            "04/29",
            "04/30",
            "05/01",
            "05/02",
            "05/03",
          ],
          userData: [
            {
              name: "用户数量",
              data: [
                27987, 4352, 4278, 3802, 377, 70, 260, 300, 158, 89,
              ],
            },
          ],
          //symbol--给拐点设置图片
          receiveData: [
            {
              name: "领取数量",
              data: [
                700,
                2670,
                3070,
                1458,
                859,
                285,
                187,
                205,
                130,
                {
                  value: 221,
                  symbol:
                    "image://https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
                  symbolSize: 30,
                },
              ],
            },
          ],
        };

      timeData = res.xAxis; //x轴的数据：日期
      userData = res.userData[0].data; //
      receiveData = res.receiveData[0].data; //
      this.option.xAxis[0].data = res.xAxis; //x轴的数据：日期

      let echartData = [
        {
          name: "用户数量",
          data: userData,
          color: "#02a9f1",
          echartType: "bar",
          yIndex: 1,
        },
        {
          name: "领取数量",
          data: receiveData,
          color: "#ff8400",
          echartType: "line",
          yIndex: 0,
        },
      ];
      for (let i = 0; i < echartData.length; i++) {
        this.option.series.push({
          name: echartData[i].name,
          type: echartData[i].echartType,
          itemStyle: {
            normal: {
              lineStyle: {
                width: 3, //折线图的粗细
              },
            },
          },
          // barWidth: 6,
          smooth: true, //让曲线平滑
          yAxisIndex: echartData[i].yIndex, //用的第几个y轴
          color: echartData[i].color,
          data: echartData[i].data,
        });
      }

      let chartDom = this.$refs.chart;
      let chartDom2 = this.$refs.chart2;
      let chartDom3 = this.$refs.chart3;
      let chartDom4 = this.$refs.chart4;
      let myChart = this.$echarts.init(chartDom); //初始化echarts实例
      let myChart2 = this.$echarts.init(chartDom2); //初始化echarts实例
      let myChart3 = this.$echarts.init(chartDom3); //初始化echarts实例
      let myChart4 = this.$echarts.init(chartDom4); //初始化echarts实例
      myChart.setOption(this.option, true);
      myChart2.setOption(this.option, true);
      myChart3.setOption(this.option, true);
      myChart4.setOption(this.option, true);
      window.addEventListener("resize", () => {
        myChart.resize();
        myChart2.resize();
        myChart3.resize();
        myChart4.resize();
      });
      //给echart添加点击事件
      myChart.on("click", function (params) {
        console.log("params-name", params); //获取x轴的值
      });

      myChart.getZr().on("click", (params) => {
        console.log("params-整个柱状图", params); //获取x轴的值
        let pointInPixel = [params.offsetX, params.offsetY];
        if (myChart.containPixel("grid", pointInPixel)) {
          let xIndex = myChart.convertFromPixel({ seriesIndex: 0 }, [
            params.offsetX,
            params.offsetY,
          ])[0];
          console.log(xIndex);
        }
      });
    },
  },
  mounted() {
    this.chartsInfo();
  },
};
</script>
<style lang="scss" scoped>
.echart {
  display: flex;
}
.statistics_eharts {
  width: calc(100vw / 2);
  height: calc(100vh / 3);
  margin-bottom: 20px;
}
.echartSet {
  margin-bottom: 20px;
  p {
    text-align: left;
    line-height: 22px;
    margin: 0;
    font-size: 14px;
  }
}
</style>
